import pygame
import random
import time

# 初始化Pygame
pygame.init()

# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("足球射门游戏")

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)

# 定义球门的位置和大小
goal_x = screen_width - 25  #左侧位置，屏幕宽-厚度
goal_y = screen_height // 2 - 50  #大门位置,height一半-门宽度一半

goal_width = 25 #大门厚度 
goal_height = 100 #门宽度

# 定义足球的初始位置和大小
ball_x = 50
ball_y = screen_height // 2
ball_size = 20
ball_speed_x = 0
ball_speed_y = 0

# 定义分数
score = 0
font = pygame.font.Font(None, 36)
mouse_font = pygame.font.Font(None, 24)

# 用于记录鼠标按下的时间和位置
mouse_pressed = False
start_time = None
click_pos = None
duration = 0

# 主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 当鼠标按下时，记录按下时间和位置
            mouse_pressed = True
            start_time = time.time()
            click_pos = event.pos
        elif event.type == pygame.MOUSEBUTTONUP and mouse_pressed:
            # 当鼠标释放时，计算点击时长并给足球一个随机的速度
            duration =time.time() - start_time
            speed_factor = min(duration / 3, 1)  # 限制最大倍数为1
            ball_speed_x = random.uniform(5, 10) * speed_factor + goal_x / screen_width * 10 * speed_factor
            ball_speed_y = random.uniform(-10, 10) * speed_factor
            mouse_pressed = False
    
    # 更新足球的位置
    ball_x += ball_speed_x
    ball_y += ball_speed_y
    
    # 检查足球是否碰到墙壁或地面
    if ball_x > screen_width or ball_y < 0 or ball_y > screen_height:
        ball_x = 50
        ball_y = screen_height // 2
        ball_speed_x = 0
        ball_speed_y = 0
    
    # 检查足球是否进入球门
    if goal_x < ball_x + ball_size and goal_x + goal_width > ball_x and goal_y < ball_y + ball_size and goal_y + goal_height > ball_y:
        score += 1
        ball_x = 50
        ball_y = screen_height // 2
        ball_speed_x = 0
        ball_speed_y = 0
    
    # 填充背景色
    screen.fill(white)
    
    # 画球门
    pygame.draw.rect(screen, green, (goal_x, goal_y, goal_width, goal_height))
    
    # 画足球
    pygame.draw.circle(screen, red, (int(ball_x), int(ball_y)), ball_size)
    
    # 显示分数
    score_text = font.render("Score: " + str(score), True, black)
    screen.blit(score_text, (10, 10))
    
    # 显示鼠标点击时的坐标及点击时长（如果有）
    if click_pos is not None:
        mouse_text = mouse_font.render(f"Mouse Click at: {click_pos} | Duration: {duration:.2f}s", True, blue)
        screen.blit(mouse_text, (10, 50))
    
    # 更新屏幕显示
    pygame.display.flip()
    
    # 控制游戏帧率
    pygame.time.Clock().tick(60)

pygame.quit()
